<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏平台 - 猜数字</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        warning: '#F59E0B'
                    },
                    fontFamily: {
                        game: ['"Press Start 2P"', 'cursive', 'sans-serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .pixel-border {
                box-shadow: 0 0 0 2px #333, 2px 2px 0 2px #333;
            }
            .game-btn {
                @apply px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200 active:scale-95;
            }
            .pulse-animation {
                animation: pulse 2s infinite;
            }
            @keyframes pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.7; }
            }
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-900 text-white font-sans min-h-screen">
<!-- 导航栏 -->
<nav class="bg-gray-800 shadow-md sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <a href="/webapp/static" class="text-xl font-bold text-primary flex items-center"><i class="fa fa-gamepad mr-2"></i>GamePlatform</a>
        <div class="hidden md:flex space-x-6 items-center">
            <a href="/webapp/static" class="text-gray-300 hover:text-white transition-colors">首页</a>
            <a href="/scoreboard.html" class="text-gray-300 hover:text-white transition-colors">排行榜</a>
            <div id="userMenu" class="hidden"><button id="userBtn" class="flex items-center text-gray-300 hover:text-white"><span id="username">游客</span><i class="fa fa-caret-down ml-1"></i></button>
                <div id="userDropdown" class="hidden absolute bg-gray-800 shadow-lg rounded-md mt-2 py-2 w-48 z-10">
                    <a href="#" class="block px-4 py-2 text-gray-300 hover:bg-gray-700">个人中心</a>
                    <a href="#" id="logoutBtn" class="block px-4 py-2 text-gray-300 hover:bg-gray-700">退出登录</a>
                </div>
            </div>
        </div>
        <button class="md:hidden text-gray-300" id="mobileMenuBtn"><i class="fa fa-bars text-xl"></i></button>
    </div>
    <div id="mobileMenu" class="hidden md:hidden bg-gray-800 border-t"><div class="container mx-auto px-4 py-3 flex flex-col space-y-3">
        <a href="/webapp/static" class="text-gray-300 hover:text-white py-2">首页</a>
        <a href="/scoreboard.html" class="text-gray-300 hover:text-white py-2">排行榜</a>
        <div id="mobileUserMenu" class="hidden py-2"><button id="mobileUserBtn" class="flex items-center text-gray-300 hover:text-white"><span id="mobileUsername">游客</span><i class="fa fa-caret-down ml-1"></i></button>
            <div id="mobileDropdown" class="hidden bg-gray-800 shadow-md rounded-md mt-2 py-2"><a href="#" class="block px-4 py-2 text-gray-300 hover:bg-gray-700">个人中心</a><a href="#" id="mobileLogoutBtn" class="block px-4 py-2 text-gray-300 hover:bg-gray-700">退出登录</a></div>
        </div>
    </div></div>
</nav>

<!-- 主内容 -->
<main class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
        <!-- 游戏标题 -->
        <div class="text-center mb-8">
            <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-game text-primary mb-2">猜数字游戏</h1>
            <p class="text-gray-400">系统已生成一个1-100之间的随机数，快来猜出它吧！</p>
        </div>

        <!-- 游戏卡片 -->
        <div class="bg-gray-800 rounded-xl shadow-lg p-6 md:p-8 pixel-border">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- 游戏区域 -->
                <div class="md:col-span-2 space-y-6">
                    <div class="bg-gray-700 rounded-lg p-6">
                        <h2 class="text-xl font-bold text-white mb-4">请输入你的猜测</h2>
                        <div class="flex space-x-4">
                            <input type="number" id="guessInput" min="1" max="100" class="flex-1 px-4 py-3 bg-gray-600 border border-gray-500 rounded-md text-white focus:outline-none focus:ring-2 focus:ring-primary/50 transition-colors" placeholder="1-100" required>
                            <button id="guessBtn" class="game-btn">猜测</button>
                        </div>
                    </div>

                    <div class="bg-gray-700 rounded-lg p-6">
                        <h2 class="text-xl font-bold text-white mb-4">游戏记录</h2>
                        <div id="guessHistory" class="space-y-2 max-h-60 overflow-y-auto pr-2">
                            <p class="text-gray-400 italic">输入数字并点击"猜测"开始游戏...</p>
                        </div>
                    </div>
                </div>

                <!-- 游戏信息 -->
                <div class="space-y-6">
                    <div class="bg-gray-700 rounded-lg p-6">
                        <h2 class="text-xl font-bold text-white mb-4">游戏状态</h2>
                        <div class="space-y-4">
                            <div>
                                <p class="text-gray-400">已猜测次数:</p>
                                <p id="guessCount" class="text-2xl font-bold text-primary">0</p>
                            </div>
                            <div>
                                <p class="text-gray-400">最佳记录:</p>
                                <p id="bestRecord" class="text-2xl font-bold text-secondary">--</p>
                            </div>
                            <div>
                                <p class="text-gray-400">当前状态:</p>
                                <p id="gameStatus" class="text-lg font-bold text-warning">未开始</p>
                            </div>
                        </div>
                    </div>

                    <div class="bg-gray-700 rounded-lg p-6">
                        <h2 class="text-xl font-bold text-white mb-4">游戏规则</h2>
                        <ul class="space-y-2 text-gray-400 text-sm">
                            <li><i class="fa fa-info-circle text-primary mr-2"></i>系统会生成一个1-100之间的随机数</li>
                            <li><i class="fa fa-info-circle text-primary mr-2"></i>每次猜测后，系统会提示"太大"或"太小"</li>
                            <li><i class="fa fa-info-circle text-primary mr-2"></i>猜中数字即获胜，记录猜测次数</li>
                            <li><i class="fa fa-info-circle text-primary mr-2"></i>次数越少，排名越高</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="text-center mt-8 space-y-4">
            <button id="newGameBtn" class="px-6 py-3 bg-secondary text-white rounded-md hover:bg-secondary/90 transition-colors duration-200 active:scale-95">
                <i class="fa fa-refresh mr-2"></i> 开始新游戏
            </button>
            <a href="/webapp/static" class="px-6 py-3 bg-gray-600 text-white rounded-md hover:bg-gray-500 transition-colors duration-200 active:scale-95">
                <i class="fa fa-home mr-2"></i> 返回首页
            </a>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-gray-800 text-gray-400 py-6 mt-12">
    <div class="container mx-auto px-4 text-center">
        <p>© 2025 GamePlatform. 保留所有权利。</p>
    </div>
</footer>

<!-- 通知组件 -->
<div id="toast" class="fixed top-20 right-4 max-w-xs bg-gray-800 text-white rounded-lg shadow-lg p-4 transform transition-all duration-300 translate-x-full z-50"><div class="flex items-start">
    <div class="mr-3 mt-1"><i class="fa fa-info-circle text-primary text-lg"></i></div>
    <div class="flex-1"><h4 id="toastTitle" class="font-bold text-white">通知</h4>
        <p id="toastMsg" class="text-gray-300 text-sm mt-1">内容将显示在这里</p>
    </div>
    <button id="closeToast" class="text-gray-400 hover:text-white"><i class="fa fa-times"></i></button>
</div></div>

<script>
    // 游戏状态
    let game = {
        secretNumber: null,
        guessCount: 0,
        bestRecord: 0,
        isGameOver: false
    };

    // API 地址
    const API_URL = '/api';

    // 显示通知
    function showToast(title, msg, type = 'info') {
        const toast = document.getElementById('toast');
        const titleEl = document.getElementById('toastTitle');
        const msgEl = document.getElementById('toastMsg');
        const icon = toast.querySelector('i');

        titleEl.textContent = title;
        msgEl.textContent = msg;

        // 设置图标和颜色
        icon.className = 'mr-3 mt-1 fa';
        if (type === 'success') {
            icon.classList.add('fa-check-circle', 'text-secondary');
        } else if (type === 'error') {
            icon.classList.add('fa-exclamation-circle', 'text-danger');
        } else {
            icon.classList.add('fa-info-circle', 'text-primary');
        }

        // 显示通知
        toast.classList.remove('translate-x-full');
        toast.classList.add('translate-x-0');

        // 自动关闭
        setTimeout(() => {
            toast.classList.remove('translate-x-0');
            toast.classList.add('translate-x-full');
        }, 3000);
    }

    // 检查登录状态
    function checkLogin() {
        fetch(`${API_URL}/auth/status`)
            .then(res => res.json())
            .then(data => {
                if (data.loggedIn) {
                    document.getElementById('username').textContent = data.username;
                    document.getElementById('mobileUsername').textContent = data.username;
                    document.getElementById('userMenu').classList.remove('hidden');
                    document.getElementById('mobileUserMenu').classList.remove('hidden');

                    // 加载最佳记录
                    fetch(`${API_URL}/game/guess/record/${data.username}`)
                        .then(res => res.json())
                        .then(record => {
                            if (record && record.bestCount > 0) {
                                document.getElementById('bestRecord').textContent = record.bestCount;
                                game.bestRecord = record.bestCount;
                            }
                        })
                        .catch(err => console.error('加载最佳记录失败:', err));
                }
            })
            .catch(err => console.error('登录状态检查失败:', err));
    }

    // 开始新游戏
    function startNewGame() {
        game.secretNumber = Math.floor(Math.random() * 100) + 1;
        game.guessCount = 0;
        game.isGameOver = false;

        document.getElementById('guessInput').value = '';
        document.getElementById('guessCount').textContent = '0';
        document.getElementById('gameStatus').textContent = '游戏进行中';
        document.getElementById('gameStatus').className = 'text-lg font-bold text-warning';
        document.getElementById('guessHistory').innerHTML = '<p class="text-gray-400 italic">输入数字并点击"猜测"开始游戏...</p>';

        showToast('新游戏开始', '系统已生成随机数，开始猜测吧！');
        document.getElementById('guessInput').focus();
    }

    // 移动端菜单切换
    document.getElementById('mobileMenuBtn').addEventListener('click', () => {
        document.getElementById('mobileMenu').classList.toggle('hidden');
    });

    // 用户下拉菜单切换
    document.getElementById('userBtn').addEventListener('click', () => {
        document.getElementById('userDropdown').classList.toggle('hidden');
    });
    document.getElementById('mobileUserBtn').addEventListener('click', () => {
        document.getElementById('mobileDropdown').classList.toggle('hidden');
    });

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', logout);
    document.getElementById('mobileLogoutBtn').addEventListener('click', logout);

    function logout() {
        fetch(`${API_URL}/auth/logout`, { method: 'POST' })
            .then(res => {
                if (res.ok) {
                    window.location.href = '..';
                } else {
                    showToast('退出失败', '服务器错误，请稍后再试', 'error');
                }
            })
            .catch(err => {
                console.error('退出登录失败:', err);
                showToast('退出失败', '发生未知错误，请稍后再试', 'error');
            });
    }

    // 猜测数字
    document.getElementById('guessBtn').addEventListener('click', guessNumber);
    document.getElementById('guessInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            guessNumber();
        }
    });

    function guessNumber() {
        if (game.isGameOver) return;

        const guess = parseInt(document.getElementById('guessInput').value);
        const guessHistory = document.getElementById('guessHistory');
        const guessCountEl = document.getElementById('guessCount');

        if (isNaN(guess) || guess < 1 || guess > 100) {
            showToast('输入错误', '请输入1-100之间的数字', 'error');
            document.getElementById('guessInput').value = '';
            document.getElementById('guessInput').focus();
            return;
        }

        game.guessCount++;
        guessCountEl.textContent = game.guessCount;
        document.getElementById('guessInput').value = '';

        let message = '';
        let className = 'text-gray-400';

        if (guess === game.secretNumber) {
            message = `恭喜！你猜中了！正确数字是 ${game.secretNumber}，共猜测了 ${game.guessCount} 次`;
            className = 'text-secondary font-bold';
            game.isGameOver = true;
            document.getElementById('gameStatus').textContent = '游戏结束';
            document.getElementById('gameStatus').className = 'text-lg font-bold text-secondary';

            // 保存分数
            if (document.getElementById('username').textContent !== '游客') {
                fetch(`${API_URL}/game/guess/score`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: document.getElementById('username').textContent,
                        gameType: 'guess',
                        score: game.guessCount
                    })
                })
                    .then(res => {
                        if (res.ok) {
                            return res.json();
                        } else if (res.status === 400) {
                            throw new Error('分数不够好，未更新记录');
                        } else {
                            throw new Error('服务器错误，请稍后再试');
                        }
                    })
                    .then(data => {
                        if (data.updated) {
                            showToast('新记录！', `恭喜你创造了新的个人记录：${game.guessCount}次`, 'success');
                            document.getElementById('bestRecord').textContent = game.guessCount;
                            game.bestRecord = game.guessCount;
                        } else {
                            showToast('游戏完成', '你的分数已提交，但未打破个人记录', 'info');
                        }
                    })
                    .catch(err => {
                        showToast('记录失败', err.message, 'error');
                    });
            }
        } else if (guess < game.secretNumber) {
            message = `你猜的数字太小了，再大一点！`;
            className = 'text-warning';
        } else {
            message = `你猜的数字太大了，再小一点！`;
            className = 'text-warning';
        }

        const messageEl = document.createElement('p');
        messageEl.className = className;
        messageEl.innerHTML = `<i class="fa fa-user mr-2"></i>${message}`;
        guessHistory.insertBefore(messageEl, guessHistory.firstChild);

        document.getElementById('guessInput').focus();
    }

    // 开始新游戏按钮
    document.getElementById('newGameBtn').addEventListener('click', startNewGame);

    // 关闭通知
    document.getElementById('closeToast').addEventListener('click', () => {
        document.getElementById('toast').classList.add('translate-x-full');
    });

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', () => {
        checkLogin();
        startNewGame();

        // 导航栏滚动效果
        window.addEventListener('scroll', () => {
            const nav = document.querySelector('nav');
            if (window.scrollY > 10) {
                nav.classList.add('py-2');
                nav.classList.remove('py-3');
            } else {
                nav.classList.add('py-3');
                nav.classList.remove('py-2');
            }
        });
    });
</script>
</body>
</html>